package com.tmpt.dao.impl;


import com.google.common.base.Strings;
import com.googlecode.genericdao.search.Search;
import com.tmpt.beans.A1TemplateColumn;
import com.tmpt.beans.A1TemplateColumnOption;
import com.tmpt.beans.A1TemplateColumnOptionData;
import com.tmpt.beans.A1TemplateTable;
import com.tmpt.dao.intf.IA1TemplateColumnOptionDataDao;
import com.tmpt.dto.A1TemplateColumnDto;
import com.tmpt.dto.Result;
import com.tmpt.enums.DataLimitType;
import com.tmpt.service.utils.CommonDbDao;
import com.tmpt.utils.FenAndYuan;
import com.tmpt.utils.StringUtils;
import com.tmptSource.bean.A1templatecolumn;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;

@Repository
public class TemplateUtils{

	@Resource
	private IA1TemplateColumnOptionDataDao optionDataDao;
	private CommonDbDao commonDao = new CommonDbDao();

	/**
	 * 验证参数合法性，防止SQL注入
	 * @param tableName
	 * @param columnName
	 * @param sortOrder
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	public boolean check(String tableName,String columnName,String sortOrder, Connection connection) throws SQLException {
		if(!commonDao.hasTable(connection, tableName)){
			return false;
		}
		if(!"".equals(columnName) && !commonDao.hasColumn(connection, tableName, columnName)){
			return false;
		}
		if(!"desc".equals(sortOrder) && !"asc".equals(sortOrder) && !"".equals(sortOrder)){
			return false;
		}
		return true;
	}


	public boolean check(String tableName,String columnName, Session session){
		Map<String,Boolean> resultMap = new HashMap<>();
		session.doWork(new Work() {
			@Override
			public void execute(Connection connection) throws SQLException {
				//验证参数合法性，防止SQL注入
				try {
					resultMap.put("check",true);
					if(!check(tableName,columnName,"",connection)){
						resultMap.put("check",false);
						//throw new SQLException("参数非法："+tableName+";"+columnName+";");
					}
				}catch (SQLException e){
					resultMap.put("check",false);
					//throw new SQLException(e);
				}
			}
		});
		return resultMap.get("check");
	}

	/**
	 * check 多列情况,Struture:“name,sex,status”
	 * @param tableName
	 * @param columnNames
	 * @param session
	 * @return
	 */
	public boolean check4multiColumns(String tableName,String columnNames, Session session){
		Map<String,Boolean> resultMap = new HashMap<>();
		session.doWork(new Work() {
			@Override
			public void execute(Connection connection) throws SQLException {
				//验证参数合法性，防止SQL注入
				try {
					resultMap.put("check", true);
					List<String> columnNameList = Arrays.asList(columnNames.split(","));
					for(String columnName: columnNameList){
						if(!check(tableName,columnName,"",connection)){
							resultMap.put("check",false);
							//throw new SQLException("参数非法："+tableName+";"+columnName+";");
						}
					}
				}catch (SQLException e){
					resultMap.put("check",false);
					//throw new SQLException(e);
				}

			}
		});
		return resultMap.get("check");
	}

	/**
	 * create a new table , by the param tablename, so check the legality
	 * @param tableName
	 * @return
	 */
	public boolean checkTableNameLegality(String tableName){
		if(tableName.length()<15){
			return true;
		}
		//用正则表达式判断表名合法性
		//..
		return false;
	}

	/**
	 * add a new column, by the param columnName, so check the legality
	 * @param columnName
	 * @return
	 */
	public boolean checkColumnNameLegality(String columnName){
		if(columnName.length()<15){
			return true;
		}
		//用正则表达式判断表名合法性
		//..
		return false;
	}


	/**
	 *
	 * @param paramMap
	 * @param conditionMap
	 * @param columnAliasMap
	 * @param paramList
	 * @param dbcolumnsProperty
	 * @param columnTableMap
	 * @param transferA1TemplateColumnMap
	 * @param table
	 * @param params:数据访问边界
	 * @return
	 */
	public String loadConditions(Map<String,String[]> paramMap, Map<String ,String> conditionMap,
								 Map<String,String> columnAliasMap, List<Object> paramList,
								 Map<String,Map<String,String>> dbcolumnsProperty,Map<String,String> columnTableMap,
								 Map<String,A1TemplateColumn> transferA1TemplateColumnMap, A1TemplateTable table
								,String[] params){
		StringBuilder sb = new StringBuilder();
		//boolean hasDeleteflagInCondition = false;

		sb.setLength(0);
		Iterator<String> it = paramMap.keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			String value = paramMap.get(key)[0];
			if(key.equals("_keyRandom") ||
					key.equals("page") ||
					key.equals("rows") ||
					key.equals("pageCurrent") ||
					key.equals("pageSize") ||
					key.equals("sortOrder") ||
					key.equals("sortColumn") ||
					key.equals("_historyId")
					){
				continue;
			}
			conditionMap.put(key, value);

			//取出column_name
			String columnName = key;
			if(key.indexOf("_Start")!=-1 || key.indexOf("_End")!=-1 || key.indexOf("_Like")!=-1){
				columnName = key.substring(0,key.lastIndexOf("_"));
			}
			/*if(columnName.toLowerCase().contains("deleteflag")){
				hasDeleteflagInCondition = true;
			}*/
			String dataType = "";
			String column_TableName = columnTableMap.get(columnName);
			String dbcolumnsPropertyKey = column_TableName+"_"+columnName;
			if(dbcolumnsProperty.get(dbcolumnsPropertyKey)!=null){
				dataType = dbcolumnsProperty.get(dbcolumnsPropertyKey).get("data_type");
			}
			//查询类型，between,left like, right like, like ...
			A1TemplateColumn a1TemplateColumn = transferA1TemplateColumnMap.get(columnName);
			if(a1TemplateColumn == null){
				continue;
			}
			String queryType = a1TemplateColumn.getQueryType();
			String dataTransfer = a1TemplateColumn.getDataTransfer();

			//
			if(key.indexOf("_Start")!=-1){
				key = key.substring(0,key.indexOf("_Start"));
				if(value instanceof String){
					//加别名
					if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
						key = columnAliasMap.get(key)+"."+key;
					}
					sb.append(key).append(">=?");

					//int类型的数据需要转换才能作比较
					if("fen2yuan".equalsIgnoreCase(dataTransfer)){
						paramList.add(FenAndYuan.yuan2fenLng(value));
					}else if("int".equalsIgnoreCase(dataType) || "bigint".equalsIgnoreCase(dataType)|| "long".equalsIgnoreCase(dataType)){
						paramList.add(Integer.parseInt(value));
					}else if("datetime".equalsIgnoreCase(dataType) || "date".equalsIgnoreCase(dataType) || "timestamp".equalsIgnoreCase(dataType)){
						paramList.add(parseTimestamp(value," 00:00:00"));
					}else {
						paramList.add(value);
					}

					/*if(key.contains("date") && !value.contains(":")) {
						value += " 00:00:00";
					}
					paramList.add(parseTimestamp(value));*/
				}
			}
			else if(key.indexOf("_End")!=-1){
				key = key.substring(0,key.indexOf("_End"));
				if(value instanceof String){
					//加别名
					if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
						key = columnAliasMap.get(key)+"."+key;
					}
					sb.append(key).append("<=?");

					//int类型的数据需要转换才能作比较
					if("fen2yuan".equalsIgnoreCase(dataTransfer)){
						paramList.add(FenAndYuan.yuan2fenLng(value));
					}else if("int".equalsIgnoreCase(dataType) || "bigint".equalsIgnoreCase(dataType)|| "long".equalsIgnoreCase(dataType)){
						paramList.add(Integer.parseInt(value));
					}else if("datetime".equalsIgnoreCase(dataType) || "date".equalsIgnoreCase(dataType) || "timestamp".equalsIgnoreCase(dataType)){
						paramList.add(parseTimestamp(value," 23:59:59.999"));
					}else {
						paramList.add(value);
					}

					/*if(key.contains("date") && !value.contains(":")){
						value = value+" 23:59:59.999";
					}else{
					}
					//日期类型的参数值转换为timestamp格式 by xiaohui
					paramList.add(parseTimestamp(value));*/
				}
			}
			else if(queryType!=null && queryType.contains("like")){
				//加别名
				if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
					key = columnAliasMap.get(key)+"."+key;
				}
				sb.append(key).append(" like ? ");
				String value1 = value;
				if(queryType.equalsIgnoreCase("like")) {
					value1 = "%"+value+"%";
				}else if(queryType.equalsIgnoreCase("left like")) {
					value1 = "%"+value+"";
				}else if(queryType.equalsIgnoreCase("right like")) {
					value1 = ""+value+"%";
				}
				paramList.add(value1);
			}
			else if("datetime".equalsIgnoreCase(dataType) || "date".equalsIgnoreCase(dataType) || "timestamp".equalsIgnoreCase(dataType)){
				//balance_date,单个日期查询
				//加别名
				if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
					key = columnAliasMap.get(key)+"."+key;
				}
				sb.append(key).append(" between ? and ? ");
				paramList.add(parseTimestamp(value," 00:00:00.0"));
				paramList.add(parseTimestamp(value," 23:59:59.999"));
			}
			else if(value instanceof String){
				//加别名
				if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
					key = columnAliasMap.get(key)+"."+key;
				}
				sb.append(key).append("=?");

				//int类型的数据需要转换才能作比较
				if("fen2yuan".equalsIgnoreCase(dataTransfer)){
					paramList.add(FenAndYuan.yuan2fenLng(value));
				}else if("int".equalsIgnoreCase(dataType) || "bigint".equalsIgnoreCase(dataType)|| "long".equalsIgnoreCase(dataType)){
					paramList.add(Integer.parseInt(value));
				}else {
					paramList.add(value);
				}
				/*String dateType1 = dbcolumnsProperty.get(key).get("data_type");
				String dateType2 = dbcolumnsProperty.get(key.substring(key.lastIndexOf(".")+1)).get("data_type");
				if("int".equalsIgnoreCase(dateType1) || "int".equalsIgnoreCase(dateType2)
						|| "bigint".equalsIgnoreCase(dateType1) || "bigint".equalsIgnoreCase(dateType2)
						|| "long".equalsIgnoreCase(dateType1) || "long".equalsIgnoreCase(dateType2)){
					paramList.add(Integer.parseInt(value));
				}else if("datetime".equalsIgnoreCase(dateType1) || "datetime".equalsIgnoreCase(dateType2)
						|| "date".equalsIgnoreCase(dateType1) || "date".equalsIgnoreCase(dateType2)
						|| "timestamp".equalsIgnoreCase(dateType1) || "timestamp".equalsIgnoreCase(dateType2)){
					paramList.add(parseTimestamp(value));
				}else {
					paramList.add(value);
				}*/
			}

			sb.append(" and ");
		}

		if(sb.length()>4)sb.delete(sb.length()-4, sb.length());

		//加载数据边界控制sql
		dataLimitTypeCondition(sb,columnAliasMap,paramList,table,params);


		//看看查询条件中有没有deleteflag
		boolean hasDeleteflagInConditionInDb = false;
		for(A1TemplateColumn column : table.getA1TemplateColumnList()){
			if(column.getIsQuery()==1 && column.getColumnName().equalsIgnoreCase("deleteflag")){
				hasDeleteflagInConditionInDb = true;
			}
		}
		if(/*!hasDeleteflagInCondition && */!hasDeleteflagInConditionInDb){
			String key = "deleteflag";
			//加别名
			int value = 0;
			if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
				key = columnAliasMap.get(key)+"."+key;
			}
			if(sb.length()>4){
				sb.append(" and ");
			}
			sb.append(key).append("=? ");
			paramList.add(value);
			conditionMap.put(key, "" + value);
		}

		return sb.toString();
	}

	private void dataLimitTypeCondition(StringBuilder sb,Map<String,String> columnAliasMap,List<Object> paramList,A1TemplateTable table, String ... params){
		//已有where条件了，加and 拼接上去
		if(sb.length()>4){
			sb.append(" and ");
		}

		int dataLimitType = Integer.parseInt(params[0]);
		int userId = Integer.parseInt(params[1]);
		int companyId = Integer.parseInt(params[2]);

		List<String> columnStrList = new ArrayList<>();
		for(A1TemplateColumn a1TemplateColumn : table.getA1TemplateColumnList()){
			columnStrList.add(a1TemplateColumn.getColumnName());
		}

		if(dataLimitType == DataLimitType.OnlyMySelf.getKeyNameInt()){
			String key = "createman_id";
			if(!columnStrList.contains(key)){
				return;
			}
			if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
				key = columnAliasMap.get(key)+"."+key;
			}
			sb.append(key).append("=? ");
			paramList.add(userId);
		}
		else if(dataLimitType == DataLimitType.LowPost.getKeyNameInt()){
			String key = "createman_id";
			if(!columnStrList.contains(key)){
				return;
			}
			if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
				key = columnAliasMap.get(key)+"."+key;
			}
			sb.append(key).append(" in (select low_user_id from a2low_user_tmp where user_id=? and user_type=1) ");
			paramList.add(userId);
		} else if(dataLimitType == DataLimitType.SamePostAndLowPost.getKeyNameInt()){
			//员工类型:1,下属员工; 2,同岗位同级员工, 目前只有这两个类型，所以先不加这个条件：and (user_type=1 or user_type=2)
			String key = "createman_id";
			if(!columnStrList.contains(key)){
				return;
			}
			if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
				key = columnAliasMap.get(key)+"."+key;
			}
			sb.append(key).append(" in (select low_user_id from a2low_user_tmp where user_id=?) ");
			paramList.add(userId);
		}
		else if(dataLimitType == DataLimitType.LowCompany.getKeyNameInt()) {
			String key = "company_id";
			if(!columnStrList.contains(key)){
				return;
			}
			if(columnAliasMap!=null && columnAliasMap.containsKey(key)){
				key = columnAliasMap.get(key)+"."+key;
			}
			sb.append(key).append("=? ");
			paramList.add(companyId);
		}
		else if(dataLimitType == DataLimitType.All.getKeyNameInt()){
			if(sb.length()>4){sb.delete(sb.length()-4,sb.length());}
		}
		else{
			sb.append(" 1!=1 ");
		}
	}

	/**
	 * 将字符串格式的日期转换为timestamp格式的
	 * @param date 日期格式为yyyy-MM-dd 或者 yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	private Timestamp parseTimestamp(String date){
		if(date.trim().length() == 10){
			date += " 00:00:00";
		}
		return Timestamp.valueOf(date);
	}

	private Timestamp parseTimestamp(String date, String datetail){
		if(date.trim().length() == 10){
			date += datetail;
		}
		return Timestamp.valueOf(date);
	}

	/**
	 *
	 * 其中sbColumnSum以下方法获取：
	 * 整理合计字段 eg:sum(balance) ;
	 * columnNameSqlSum 不存在时，使用拼接方法sum+(column)；
	 * columnNameSqlSum 存在时，使用columnNameSqlSum字段 ，分以下两种情况处理:
	 * needSum = 1时，使用拼接方法sum+(column);
	 * needSum = 2时，columnNameSqlSum中可能是文字（eg:合计），直接使用
	 * @param sbColumn
	 * @param sbColumnSum
	 * @param columnList
	 */
	public void loadColumnString(StringBuilder sbColumn, StringBuilder sbColumnSum, List<A1TemplateColumn> columnList,
								 Map<String,String> columnAliasMap,Map<String,
								Map<String,String>> dbcolumnsProperty,Map<String,String> columnTableMap){
		//多值的列，拼成json返回给页面
		//JSONArray jsonArrayColumnOptions = new JSONArray();
		//for 处理一下每一列信息
		//loadColumnOptionList 将dataResoure=5，数据字典中数据，加载到column的option中了
		for(A1TemplateColumn columnMap:columnList){
			String columnTableAliasName = columnMap.getTableAliasName();
			String tableAliasName = columnMap.getA1TemplateTable().getTableAliasName();
			String columnName = columnMap.getColumnName();
			int needSum = columnMap.getNeedSum();
			String columnNameSqlSum = columnMap.getColumnNameSqlSum();
			int dataResource = columnMap.getDataResource();
			String dataType = "";
			String column_TableName = columnTableMap.get(columnName);
			String dbcolumnsPropertyKey = column_TableName+"_"+columnName;
			if(dbcolumnsProperty.get(dbcolumnsPropertyKey)!=null){
				dataType = dbcolumnsProperty.get(dbcolumnsPropertyKey).get("data_type");
			}
			//生成columnNameSql
			String columnNameSql = columnMap.getColumnNameSql();
			//有可能本身有值，直接使用
			if(StringUtils.isNull(columnNameSql)){
				if(!StringUtils.isNull(columnTableAliasName)){
					columnNameSql = columnTableAliasName+"."+columnName;
				}else if(!StringUtils.isNull(tableAliasName)){
					columnNameSql = tableAliasName+"."+columnName;
				}
			}

			//ps:状态status： 1=有效，0=无效
			List<A1TemplateColumnOption> a1TemplateColumnOptionList = columnMap.getA1TemplateColumnOptionList();

			//loadColumnOptionList 将dataResoure=5，数据字典中数据，加载到column的option中了
			//dataResource==4,如，date,datetime,combobox,combotree,是辅助select框，keyName=valueName的，所以查询时直接显示
			if((dataResource == A1TemplateColumnDto.dataResource_OptionsTable
					|| dataResource == A1TemplateColumnDto.dataResource_Sql
					|| dataResource == A1TemplateColumnDto.dataResource_ColumnOptionData) && a1TemplateColumnOptionList.size()>0){//有多值选择，key-value形式; case status when 1 then '有效' when 0 then '无效' end
				if(columnNameSql!=null && !columnNameSql.trim().equals("")){
					sbColumn.append("case ").append(columnNameSql).append(" ");
				}else{
					sbColumn.append("case ").append(columnName).append(" ");
				}
				for(A1TemplateColumnOption option: a1TemplateColumnOptionList){
					String keyName = option.getKeyName();
					String valueName=option.getValueName();
					if(!Strings.isNullOrEmpty(dataType) &&
							(dataType.equalsIgnoreCase("int") || dataType.equalsIgnoreCase("bigint") || dataType.equalsIgnoreCase("long"))) {
						sbColumn.append("when ").append(keyName).append(" then '").append(valueName).append("' ");
					}else{
						sbColumn.append("when '").append(keyName).append("' then '").append(valueName).append("' ");
					}
				}
				sbColumn.append("end ");
				sbColumn.append(" as ").append(columnName).append("_Str,");
			}
			/*//日期格式，查询时。 注掉，通过java对返回的ResultSet处理，提高数据库兼容性
			if(!Strings.isNullOrEmpty(dataType) &&
					(dataType.equalsIgnoreCase("datetime") || dataType.equalsIgnoreCase("date") || dataType.equalsIgnoreCase("timestamp"))){

			}*/
			//else{
			if(columnNameSql!=null && !columnNameSql.trim().equals("")){
				sbColumn.append(columnNameSql).append(" as ").append(columnName);
			}else{
				sbColumn.append(columnName);
			}
			//}
			sbColumn.append(",");
			
			//Sum columns
			if(needSum>=1){
				if(columnNameSqlSum!=null && !columnNameSqlSum.trim().equals("")){
					if(needSum==2){
						sbColumnSum.append("'").append(columnNameSqlSum).append("'").append(" as ").append(columnName);
					}else{
						sbColumnSum.append(columnNameSqlSum).append(" as ").append(columnName);
					}
				}else{
					sbColumnSum.append("sum(").append(columnName).append(") as ").append(columnName);
				}
				sbColumnSum.append(",");
			}
		}
		if(sbColumn.length()>3)
			sbColumn.delete(sbColumn.length()-1, sbColumn.length());
		if(sbColumnSum.length()>3)
			sbColumnSum.delete(sbColumnSum.length()-1, sbColumnSum.length());
	}


	/**
	 * 将dataResoure=5，数据字典中数据，加载到column的option中
	 * @param columnList
	 */
	public void loadColumnOptionList(List<A1TemplateColumn> columnList){

		for(A1TemplateColumn column : columnList){
			String columnName = column.getColumnName();
			int dataResource = column.getDataResource();
			List<A1TemplateColumnOption> columnOptionList = column.getA1TemplateColumnOptionList();

			//从数据字典取数据
			if(dataResource == 5) {
				//清空原数据
				columnOptionList.clear();
				//从数据字典取数据
				Search search = new Search();
				search.addFilterEqual("columnName",columnName);
				List<A1TemplateColumnOptionData> columnOptionDataList = optionDataDao.search(search);
				for (A1TemplateColumnOptionData columnOptionData : columnOptionDataList) {
					String columnNameData = columnOptionData.getColumnName();
					String keyNameData = columnOptionData.getKeyName();
					String valueNameData = columnOptionData.getValueName();
					//生成新的option对象存入column option下
					A1TemplateColumnOption columnOption = new A1TemplateColumnOption();
					columnOption.setKeyName(keyNameData);
					columnOption.setValueName(valueNameData);
					columnOptionList.add(columnOption);
				}
			}

		}
	}

	public Map<String,String> loadColumnTableAlias(A1TemplateTable table){
		Map<String,String> columnAliasMap = new HashMap<String, String>();
		String aliasNameTable = table.getTableAliasName();
		
		for(A1TemplateColumn column : table.getA1TemplateColumnList()){
			//if(column.getIsQuery() != 1){continue;}
			String aliasNameColumn = column.getTableAliasName();
			//字段对应别名为空时，用表别名
			if(StringUtils.isNull(aliasNameColumn) && !StringUtils.isNull(aliasNameTable)){
				aliasNameColumn = aliasNameTable;
			}
			if(!StringUtils.isNull(aliasNameColumn)){
				columnAliasMap.put(column.getColumnName(), aliasNameColumn);
			}
		}
		
		return columnAliasMap;
	}

	/**
	 * 从数据库取列属性
	 * @param table
	 * @param session
	 * @return {"table_name_column_name":{"table_name":"","column_name":"","data_type":"int","length":"0"},...}
	 */
	public Map<String,Map<String,String>> loadDbcolumnsProperty(A1TemplateTable table,Session session){

		Result result = new Result();
		session.doWork(new Work() {
			@Override
			public void execute(Connection connection) throws SQLException {
				Result result1 = queryRalationTableList(table);
				List<String> tableNameList = (List<String>)result1.getResultMap().get("tableNameList");
				Map<String,Map<String,String>> dbcolumnsProperty = commonDao.queryColumnsProperty(connection,tableNameList);
				result.getResultMap().put("dbcolumnsProperty",dbcolumnsProperty);
			}
		});

		/*Map<String,String> columnDataTypeMap = new HashMap<String, String>();
		for(A1TemplateColumn column : table.getA1TemplateColumnList()){
			String columnDataType = column.getColumnDataType();
			columnDataTypeMap.put(column.getColumnName(), columnDataType);
		}*/
		return (Map<String,Map<String,String>>)result.getResultMap().get("dbcolumnsProperty");
	}

	/**
	 * 查询所有联系表
	 * @param table
	 * @return
	 */
	public Result queryRalationTableList(A1TemplateTable table){
		Result result = new Result();
		List<String> tableNameList = new ArrayList<>();
		Map<String,String> columnTableMap = new HashMap<>();
		List<A1TemplateColumn> columnList = table.getA1TemplateColumnList();
		//主表名字
		String tableNameMaster = table.getTableName();
		tableNameList.add(tableNameMaster);
		int mode = table.getMode();
		String sql = "";
		/*0	表名直接拼接SQL
		1	TableNameSql里写表名join语句
		2	按规则自定义SQL
		3	BeanObject指定调用对象方法*/
		switch (mode){
			case 1:{
				sql = table.getTableNameSql();
				break;
			}
			case 2:{
				sql = table.getSqlPage();
				break;
			}
			case 0:
			default:{
				for(A1TemplateColumn column:columnList){
					String columnName = column.getColumnName();
					columnTableMap.put(columnName,tableNameMaster);
				}
				result.getResultMap().put("tableNameList",tableNameList);
				result.getResultMap().put("columnTableMap",columnTableMap);
				return result;
			}
		}
		//从表
		for(A1TemplateColumn column:columnList){
			String columnName = column.getColumnName();
			String columnTableAliasName = column.getTableAliasName();
			if(StringUtils.isNull(columnTableAliasName)){
				columnTableMap.put(columnName,tableNameMaster);
				continue;
			}
			String tableName = parseTableName(sql,columnTableAliasName);
			if(tableNameList.contains(tableName)){
				columnTableMap.put(columnName,tableName);
				continue;
			}
			tableNameList.add(tableName);
			columnTableMap.put(columnName,tableName);
		}

		result.getResultMap().put("tableNameList",tableNameList);
		result.getResultMap().put("columnTableMap",columnTableMap);
		return result;
	}

	/**
	 * 解析SQL语句中，哪些是表名
	 * @param sql
	 * @param alias
	 * @return
	 */
	private String parseTableName(String sql, String alias){
		String tableName = "";
		String[] sqlArray = sql.split(" ");
		for(int i=0;i<sqlArray.length;i++){
			String sqlData = sqlArray[i];
			if(sqlData.equalsIgnoreCase(alias)){
				tableName = sqlArray[i-1];
			}
		}
		return tableName;
	}

	public Map<String,A1TemplateColumn> transferA1TemplateColumnMap(A1TemplateTable a1TemplateTable){
		Map<String,A1TemplateColumn> a1TemplateColumnMap = new HashMap<>();
		//取出每一列的data_tranfer
		List<A1TemplateColumn> a1TemplateColumnList = a1TemplateTable.getA1TemplateColumnList();
		for(A1TemplateColumn a1TemplateColumn:a1TemplateColumnList){
			a1TemplateColumnMap.put(a1TemplateColumn.getColumnName(),a1TemplateColumn);
		}
		return a1TemplateColumnMap;
	}

	/*public static void main(String[] args) {
		String sql = "t_freight_rule_info t1 left join t_mchnt_info t2 on t1.company_id=t2.company_id";
		String alias = "t22";
	}*/
}

